import { Injectable } from '@nestjs/common';
import { CreateDictDto } from './dto/create-dict.dto';
import { UpdateDictDto } from './dto/update-dict.dto';
import { PrismaService } from 'nestjs-prisma';
import { CreateDictItemDto } from './dto/create-dict-item.dto';
import { UpdateDictItemDto } from './dto/update-dict-item.dto';

@Injectable()
export class DictService {
  constructor(private readonly prisma: PrismaService) {}
  async create(createDictDto: CreateDictDto): Promise<any> {
    return this.prisma.dict.create({ data: createDictDto });
  }

  async createItem(
    code: string,
    createDictItemDto: CreateDictItemDto,
  ): Promise<any> {
    return this.prisma.dictItem.create({
      data: {
        dictCode: code,
        ...createDictItemDto,
      },
    });
  }
  async updateItem(
    id: string,
    updateDictItemDto: UpdateDictItemDto,
  ): Promise<any> {
    return this.prisma.dictItem.update({
      where: {
        id: id,
      },
      data: updateDictItemDto,
    });
  }

  async findAll(): Promise<any> {
    return this.prisma.dict.findMany({
      orderBy: {
        weight: 'desc',
      },
      include: {
        items: true,
      },
    });
  }

  async findOne(code: string): Promise<any> {
    return this.prisma.dict.findUnique({
      where: { code: code },
      include: {
        items: {
          orderBy: {
            weight: 'desc',
          },
        },
      },
    });
  }

  async update(code: string, updateDictDto: UpdateDictDto): Promise<any> {
    return this.prisma.dict.update({
      where: { code },
      data: updateDictDto,
    });
  }

  async remove(code: string): Promise<any> {
    await this.prisma.dict.delete({
      where: { code },
    });

    return this.prisma.dictItem.deleteMany({
      where: {
        dictCode: code,
      },
    });
  }

  async removeItem(id: string): Promise<any> {
    return this.prisma.dictItem.delete({
      where: { id },
    });
  }
}
